﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Office.Interop.Word;

namespace OfficeExport
{
    /// <summary>
    /// Exports Word documents to XPS or PDF.
    /// </summary>
    public class WordExporter
        : Exporter<WordExportSettings>
    {
        /// <summary>
        /// Creates an instance of the export settings.
        /// </summary>
        /// <returns></returns>
        protected override WordExportSettings CreateSettings()
        {
            return new WordExportSettings();
        }

        /// <summary>
        /// Implements the actual export logic.
        /// </summary>
        /// <param name="sourcePath">The source path.</param>
        /// <param name="targetPath">The target path.</param>
        protected override void OnExport(string sourcePath, string targetPath)
        {
            _Application application = new Application();
            _Document document = application.Documents.Open(sourcePath);

            if (document != null) {
                try {
                    var format = WdExportFormat.wdExportFormatPDF;
                    if (this.Settings.Format == ExportFormat.Xps) {
                        format = WdExportFormat.wdExportFormatXPS;
                    }
                    var optimize = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                    if (this.Settings.OptimizeFor == OptimizeFor.Print) {
                        optimize = WdExportOptimizeFor.wdExportOptimizeForPrint;
                    }
                    var range = WdExportRange.wdExportAllDocument;
                    if (this.Settings.Range == ExportRange.FromTo) {
                        range = WdExportRange.wdExportFromTo;
                    }
                    var item = WdExportItem.wdExportDocumentContent;
                    if (this.Settings.Item == ExportItem.DocumentWithMarkup) {
                        item = WdExportItem.wdExportDocumentWithMarkup;
                    }

                    document.ExportAsFixedFormat(targetPath, format, this.Settings.OpenAfterExport, optimize, range, this.Settings.From, this.Settings.To,
                        item, this.Settings.IncludeDocProps, this.Settings.KeepIRM);
                }
                finally {
                    if (document != null) {
                        document.Close();
                        document = null;
                    }
                    application.Quit();
                    application = null;
                }
            }
        }
    }
}
